import type { UserLoginDataModel, UserLoginModel, UserModel } from '@/api/models/userModel'
import { getList, postLogin } from '@/api/user'
import { defineStore } from 'pinia'
import { router } from '@/router'

export const useUserStore = defineStore(`user-store`, {
  state: () => ({
    token: '',
    user: {} as UserModel
  }),
  persist: true,
  getters: {},
  actions: {
    async login(form: UserLoginModel) {
      const { fail, data } = await postLogin<UserLoginDataModel>(form)
      if (!fail) {
        this.token = data.token
        this.user = data.user
      }
      return !fail
    },
    logout() {
      this.$reset()
      router.push(`/login`)
    },
    async list(current: number, limit: number, key: string = '') {
      return await getList<{ list: Array<UserModel>; total: number }>({ current, limit, key })
    }
  }
})
